import { ref, onUnmounted } from 'vue'
import dayjs from 'dayjs' // 引入dayjs插件
import relativeTime from 'dayjs/plugin/relativeTime' // 引入相对时间插件
import 'dayjs/locale/zh-cn' // 引入中文语言包   默认英文语言包
// 相当于dayjs的扩展   相对时间的方法   这个方法写完之后  dayjs就有了from方法,to方法
dayjs.extend(relativeTime)

const useTime = (show = 1000) => {
  let isLoop = true
  const timeToNow = (t) => {
    const time = ref(dayjs(t).format('YYYY-MM-DD HH:mm:ss'))
    const nowTime = dayjs().valueOf()
    const diffTime = nowTime - dayjs(t).valueOf()
    if (diffTime > show * 24 * 60 * 60 * 1000) {
      isLoop = false
      return time.value
    }
    time.value = dayjs().locale('zh-cn').to(t)
    setTimeout(() => {
      if (isLoop) {
        timeToNow()
        time.value = dayjs().locale('zh-cn').to(t)
      } else {
        time.value = dayjs(t).format('YYYY-MM-DD HH:mm:ss')
      }
    }, 1000)
    return time
  }
  onUnmounted(() => {
    isLoop = null
  })
  const nowTime = (t) => {
    const time = ref(dayjs(t).format('YYYY-MM-DD HH:mm:ss'))
    return time.value
  }
  return { nowTime, timeToNow }
}
export default useTime
